<template>
  <div class="upload-container">
    <div>
      <form id="uploadForm"
            method="post"
            action=""
            @mouseenter.prevent="mouseenter()">
        <div id="selectFileBtn"
             @click="selectFile">
          <el-dropdown @command="handCommand"
                       size="small">
            <el-button type="primary"
                       size="mini"
                       style="width:100px;"
                       :style="styles"
                       :class="selfClass"
                       class="btn-select-btn btnPadding815">
              <span class="text">
                <span v-if="btnName">{{ btnName }}</span>
                <span v-else>
                  <i class="iconfont icon-shangchuan icon-14size"></i>
                  上传
                </span>
              </span>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="file">上传文件</el-dropdown-item>
                <el-dropdown-item command="folder">上传文件夹</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <input ref="uploadFile"
                 type="file"
                 name="uploadFile"
                 id="uploadFile"
                 multiple="multiple"
                 :accept="acceptType"
                 style="left:-9999px;position:absolute;"
                 @change="tirggerFile($event)" />
        </div>
      </form>
    </div>
    <!-- 上传文件主窗口 -->
    <div class="dialog-wrapper" v-if="dialogFormVisible">
      <!-- 展开的窗口 -->
      <div class="dialog-body">
        <div class="uploader-lsit-content">
          <div class="uploader-lsit-title" @click="uploadDialogToggle">
            <h3>
              <span class="select-text" v-if="fileAlreadyNum === fileList.length">上传完成</span>
              <span class="select-text" v-else>
                正在上传(<span v-if="fileList.length">{{ fileAlreadyNum + 1 }}/</span>{{ fileList.length }})
              </span>
            </h3>
            <div class="dialog-control">
              <span v-if="minmize" @click.stop="minMizeClick">-</span>
              <span class="diamonds" v-if="maximize" @click.stop="maxMizeClick"></span>
              <span @click="handleClose">x</span>
            </div>
          </div>
          <div class="uploader-list-header" v-if="minmize">
            <div class="file-name">文件名</div>
            <div class="file-size">大小</div>
            <div class="file-folder">目录</div>
            <div class="file-progress">上传进度</div>
            <div class="file-status tc">状态</div>
            <div class="file-operate">操作</div>
          </div>

          <!-- 缩小的窗口 -->
          <div class="dialog-min-header" v-if="maximize"></div>
          <div class="uploader-list" v-if="minmize">
            <ul>
              <li class="file-list" v-for="(item, index) in fileListArr" :key="index">
                <div class="info">
                  <div class="file-name">
                    <img v-if="item.pic" :src="item.pic" alt="" class="file-icon">
                    <span class="name-text">{{ item.name }}</span>
                  </div>
                  <span class="file-size">{{ sizeFormat(item.size) }}</span>
                  <span class="file-folder link-color">
                    <!-- 上传目录 -->
                    <span v-if="item.uploadPath" @click="uploadPathClick(item.uploadPath)" :title="item.uploadPath">{{ pathFormat(item.uploadPath) }}</span>
                  </span>
                  <span class="file-progress tc">
                    <span v-if="item.domprogress">{{ item.domprogress }}%</span>
                    <span v-else>0%</span>
                  </span>
                  <span class="file-status tc">
                    <span v-if="item.dompercentmb">{{ item.dompercentmb }}</span>
                    <span v-else>{{ item.domstatus }}</span>
                  </span>
                  <span v-if="item.upFileStatus && item.domprogress != 100 && item.dompercentmb && apiStatus != true" class="file-operate cursor" @click="oerateFile(item, index)">
                    暂停
                  </span>
                  <span v-if="!item.upFileStatus && item.domprogress != 100 && !apiStatus" class="file-operate cursor" @click="reUpload(item, index)">开始</span>
                  <span v-if="apiStatus && item.domprogress != 100" class="file-operate cursor" @click="reUploadStart(item, index)">
                    重新上传
                  </span>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.self-process-box {
  width: 100%;
  background: #ebeef5;
  height: 7px;
  display: flex;
  align-items: center;
  border-radius: 100px;
  .inner {
    background: #409eff;
    height: 7px;
    width: 0%;
    border-radius: 100px;
  }
}
.uploader-lsit-content {
  position: absolute;
  top: auto;
  width: 633px;
  bottom: 0px;
  right: 20px;
  background: #fff;
  z-index: 1;
  border-top-left-radius: 7px;
  border-top-right-radius: 7px;
  border: 1px solid #e2e2e2;
  box-shadow: 0 0 10px #ccc;
  margin-bottom: -2px;
  .uploader-lsit-title {
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #f7faff;
    margin-right: 50px;
    h3 {
      line-height: 44px;
      .select-text {
        font-style: normal;
        cursor: text;
        font-weight: 300;
        padding-left: 10px;
        font-size: 14px;
      }
    }
    .dialog-control {
      position: absolute;
      right: 10px;
      top: 10px;
      height: 20px;
      span {
        cursor: pointer;
        height: 20px;
        width: 20px;
        line-height: 20px;
        font-size: 20px;
        color: #a4a9b3;
        font-family: yunfont !important;
        font-style: normal;
        font-weight: 400;
        font-variant: normal;
        text-transform: none;
        line-height: 1;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        text-align: center;
        line-height: 20px;
        color: #999;
        margin: 0 2px;
      }
      .diamonds {
        display: inline-block;
        width: 10px;
        height: 10px;
        border: 1px solid #999;
      }
    }
  }
  .uploader-list-header {
    overflow: hidden;
    height: 35px;
    border-bottom: 1px solid #f2f6fd;
    line-height: 35px;
    color: #424e67;
    .file-name {
      float: left;
      width: 30%;
      text-indent: 14px;
    }
    .file-folder {
      float: left;
      width: 12%;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }
    .file-size {
      float: left;
      width: 13%;
      height: 49px;
      text-indent: 10px;
    }
    .file-progress {
      float: left;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      width: 10%;
      height: 49px;
    }
    .file-status {
      position: relative;
      float: left;
      width: 22%;
      height: 49px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    .file-operate {
      float: left;
      width: 12%;
      height: 49px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
  .uploader-list {
    position: relative;
    overflow: hidden;
    overflow-y: auto;
    height: 349px;
    margin-top: -1px;
    ul {
      li {
        position: relative;
        height: 49px;
        border-bottom: 1px solid #f2f6fd;
        line-height: 49px;
        .info {
          position: absolute;
          width: 100%;
          height: 100%;
          .file-icon {
            position: absolute;
            top: 12px;
            left: 13px;
            width: 24px;
            height: 24px;
          }
          .file-name {
            position: relative;
            float: left;
            overflow: hidden;
            width: 30%;
            height: 49px;
            white-space: nowrap;
            text-indent: 45px;
            text-overflow: ellipsis;
            .name-text {
              display: block;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }
          .file-size {
            float: left;
            width: 13%;
            height: 49px;
            text-indent: 10px;
          }
          .file-folder {
            float: left;
            width: 12%;
            height: 49px;
            text-overflow: ellipsis;
            overflow: hidden;
            white-space: nowrap;
          }
          .file-progress {
            float: left;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            width: 10%;
            height: 49px;
          }
          .file-status {
            position: relative;
            float: left;
            width: 22%;
            height: 49px;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }
          .file-operate {
            position: relative;
            float: left;
            width: 12%;
            height: 49px;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }
        }
      }
    }
  }
}
</style>

<script setup>
import { ref, reactive, computed, watch, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import SparkMD5 from 'spark-md5'
import { asyncGetData } from '@/api/fileManage'

// Props
const props = defineProps({
  pathName: {
    type: String
  },
  styles: {
    type: String
  },
  btnName: {
    type: String
  },
  selfClass: {
    type: String
  },
  acceptType: {
    type: String
  },
  noUseDialog: { //上传方式选择
    type: Boolean,
    default: false
  },
  sucaiPage: {
    type: Boolean, //素材
    default: false
  },
  folderCreatedCast: {
    type: Boolean, //创建完毕
    default: false
  }
})

// Emits
const emit = defineEmits(['uploadPath', 'folderCreatedEmit'])

// 移除Router依赖，使用简单的页面跳转实现
function navigateTo(path, query = {}) {
  // 简单的页面跳转实现
  let queryString = Object.keys(query).map(key => 
    `${encodeURIComponent(key)}=${encodeURIComponent(query[key])}`
  ).join('&')
  
  let fullPath = path + (queryString ? `?${queryString}` : '')
  
  // 在单页应用中模拟导航
  console.log(`导航到: ${fullPath}`)
  // 这里可以根据实际情况实现页面导航逻辑
}

// 本地状态管理（替代Vuex）
const localState = reactive({
  cancel_btn_states: false,
  upload_wait_status: false,
  current_space: null,
  folderAllCreated: false,
  isFolder: false,
  apiStatus: false,
  uploadAll: false,
  http_path: '',
  yun_uid: '',
  sub_id: '',
  crop_id: '',
  groupid: '',
  _token: ''
})

// 模拟Vuex的commit和dispatch方法
const commit = (mutationName, value) => {
  // 简化的状态管理
  switch(mutationName) {
    case 'CHANGE_CANCEL_FLAG':
      localState.cancel_btn_states = value
      break
    case 'ACTION_UPLOAD_WAIT_STATUS':
      localState.upload_wait_status = value
      break
    case 'ACTION_FOLDER_ALL_CREATED':
      localState.folderAllCreated = value
      break
    case 'ACTION_IS_FOLDER':
      localState.isFolder = value
      break
    case 'ACTION_API_STATUS':
      localState.apiStatus = value
      break
    case 'CHANGE_UPLOAD_ALL':
      localState.uploadAll = value
      break
    default:
      console.log('Unknown mutation:', mutationName)
  }
}

const dispatch = async (actionName, payload) => {
  // 简化的action处理
  console.log('Dispatch action:', actionName, payload)
  // 对于文件夹创建，这里直接模拟成功
  if (actionName === 'ACTION_UPLOAD_FOLDER_PATH') {
    await new Promise(resolve => setTimeout(resolve, 500))
    localState.folderAllCreated = true
    return true
  }
  return false
}

// 响应式数据
const dialogFormVisible = ref(false)
const fileList = ref([])
const urlRes = ref('') //302后的url地址1
const urlRes1 = ref('') //302后的地址2
const uploadName = ref('')
const uploadBtnFlag = ref(false) //上传按钮flag
const uid = ref('')
const timers = ref(null)
const curentTimes = ref(null)
const postTimes = ref(null)
const maximize = ref(false)
const minmize = ref(true)
const fileAlreadyNum = ref('')
const worker = ref(null)
const __folderCreated = ref(false)
const __isFolderTip = ref(false)
const fileEvent = reactive({})
const firstTimeUpload = ref(true)
const stopUpload = ref(false)
const intervalId = ref(null) //定时器刷新token
const uploadDialogFlag = ref(false)

// 引用
const uploadFile = ref(null)

// 计算属性
const fileListArr = computed(() => {
  return fileList.value
})

// 本地计算属性替代Vuex getters
const cancel_btn_states = computed(() => localState.cancel_btn_states)
const upload_wait_status = computed(() => localState.upload_wait_status)
const current_space = computed(() => localState.current_space)
const folderAllCreated = computed(() => localState.folderAllCreated)
const isFolder = computed(() => localState.isFolder)
const apiStatus = computed(() => localState.apiStatus)
const uploadAll = computed(() => localState.uploadAll)
const http_path = computed(() => localState.http_path)
const yun_uid = computed(() => localState.yun_uid)
const sub_id = computed(() => localState.sub_id)
const crop_id = computed(() => localState.crop_id)
const groupid = computed(() => localState.groupid)
const _token = computed(() => localState._token)

// 监听
watch(() => props.folderCreatedCast, (newVal) => {
  console.log('[watch] folderCreatedCast 上传完成参数监听 ' + newVal)
  if (newVal) {
    uploadFileHandle()
  }
})

watch(apiStatus, (val) => {
  console.log('[watch] apiStatus error' + val)
  if (val) {
    let fileNotAlready = fileList.value.filter(v => v.domprogress != '100')
    fileList.value.forEach((v, i) => {
      fileNotAlready.forEach(v1 => {
        if (v.name === v1.name) {
          v.domstatus = '上传失败'
          v.upFileStatus = false
          v.dompercentmb = '上传失败'
        }
      })
    })
  }
}, { deep: true, immediate: true })

watch(isFolder, (val) => {
  if (val) {
    __isFolderTip.value = true
  } else {
    __isFolderTip.value = false
  }
}, { deep: true, immediate: true })

watch(cancel_btn_states, (newValue) => {
  uploadBtnFlag.value = newValue
})

watch(upload_wait_status, (newValue) => {
  if (newValue) {
    console.log('[watch] 检测上传状态 upload-status-wait 调用 uploadFile ' + newValue)
    uploadFileHandle()
  }
})

watch(fileList, (newValue) => {
  if (newValue.length > 0) {
    let fileProgressStatues = newValue.every(v => v.domprogress == '100')
    let fileAlready = newValue.filter(v => v.domprogress == '100')
    if (fileAlready.length > 0) {
      fileAlreadyNum.value = fileAlready.length
    } else {
      fileAlreadyNum.value = ''
    }
    if (fileProgressStatues) {
      //全部上传完毕-->最小化上传列表
      commit('CHANGE_CANCEL_FLAG', true)
    commit('CHANGE_UPLOAD_ALL', true)
    commit('ACTION_FOLDER_ALL_CREATED', false)
    dispatch('ACTION_UPLOAD_FOLDER_PATH', [])
      commit('ACTION_API_STATUS', false)
      emit('folderCreatedEmit')
      firstTimeUpload.value = true
      stopUpload.value = true
      clearInterval(timers.value)
      timers.value = null
      commit('ACTION_UPLOAD_WAIT_STATUS', false)
    commit('ACTION_IS_FOLDER', false)
      if (uploadFile.value) uploadFile.value.value = ""
      window.sessionStorage.removeItem('moreFileList')
    }
  }
}, { deep: true })

// 生命周期
onMounted(() => {
  intervalId.value = setInterval(sendRequest, 3600000);
})

onBeforeUnmount(() => {
  stopUpload.value = true
  // 在组件销毁前清除定时器  
  clearInterval(intervalId.value); 
})

// 方法
// 上传过程中刷新token 防止关闭
function sendRequest() {
  // updateToken() - 这里需要根据实际情况实现
}

// file attr webkitdirectory reset.
function mouseenter() {
  if (uploadFile.value) {
    uploadFile.value.removeAttribute('webkitdirectory')
  }
  window.sessionStorage.setItem('folderFlag', false)
  window.sessionStorage.removeItem('moreFileList')
  commit('ACTION_IS_FOLDER', false)
}

// 上传方式下拉
async function handCommand(command) {
  if (command === 'folder') {
    await commit('ACTION_IS_FOLDER', true)
    if (uploadFile.value) {
      uploadFile.value.setAttribute('webkitdirectory', 'webkitdirectory')
    }
    window.sessionStorage.setItem('folderFlag', true)
    if (uploadFile.value) uploadFile.value.click();
    stopUpload.value = false
  } else {
    await commit('ACTION_IS_FOLDER', false)
    if (uploadFile.value) uploadFile.value.click();
    stopUpload.value = false
    window.sessionStorage.setItem('folderFlag', false)
  }
}

// reset status.
function resetStatus() {
  dialogFormVisible.value = false
  fileList.value = []
  firstTimeUpload.value = true
  stopUpload.value = true
  clearInterval(timers.value)
  timers.value = null
  commit('ACTION_API_STATUS', false)
  commit('CHANGE_CANCEL_FLAG', false)
  commit('ACTION_UPLOAD_WAIT_STATUS', false)
  commit('ACTION_IS_FOLDER', false)
  emit('folderCreatedEmit')
  if (uploadFile.value) uploadFile.value.value = ""
  window.sessionStorage.removeItem('moreFileList')
}

/**
 * 关闭按钮-刷新列表-重置数据
 */
async function handleClose() {
  let fileProgressStatues = fileList.value.every(v => v.domprogress == '100')
  if (!fileProgressStatues) {
    try {
      await ElMessageBox.confirm('列表中有未上传完成的文件,确定要放弃上传吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
      dialogFormVisible.value = false
      fileList.value = []
      firstTimeUpload.value = true
      stopUpload.value = true
      clearInterval(timers.value)
      timers.value = null
      await commit('ACTION_API_STATUS', false)
      await commit('CHANGE_CANCEL_FLAG', true)
      await commit('ACTION_UPLOAD_WAIT_STATUS', false)
      await commit('ACTION_IS_FOLDER', false)
      emit('folderCreatedEmit')
      if (uploadFile.value) uploadFile.value.value = ""
      window.sessionStorage.removeItem('moreFileList')
    } catch (error) {
      // 用户取消操作
    }
  } else {
    resetStatus()
  }
}

/**
 * 暂停上传
 * @param {Object} item
 * @param {Number} index
 */
function oerateFile(item, index) {
  console.log(item, index)
  fileList.value.forEach((v, i) => {
    if (item.name === v.name) {
      v.upFileStatus = false
    }
  })
}

/**
 * 重置重传状态
 * @param {Object} item
 */
function resetUpladStatus(item) {
  fileList.value.forEach((v, i) => {
    if (v.domprogress != 100) {
      v.upFileStatus = true
      v.domstatus = '排队中'
      delete v.dompercentmb
    }
    if (item) {
      if (item.name === v.name) {
        v.upFileStatus = true
        uploadFileProcess(v, v.md5File)
      }
    } else {
      v.upFileStatus = true
    }
  })
}

/**
 * 重新上传
 * @param {Object} item
 * @param {Number} index
 */
async function reUpload(item, index) {
  //重新上传--断网或接口异常,仅限判断最后一次操作的文件/文件夹
  let foderFlag = window.sessionStorage.getItem('folderFlag')
  let testNetwork = await asyncGetData("getlist", '/').then(res => {
    const { data } = res;
    if (data.code == '200') {
      return true
    }
  }).catch(() => {
    testNetwork = false
  })
  //当前网络ok
  if (testNetwork) {
    commit('ACTION_API_STATUS', false)
      //接口异常or网络失败中断
      if (apiStatus.value != true) {
        //状态重置
        if (foderFlag === 'true') {
          //文件夹未创建--文件夹创建完毕--自动上传
          if (!props.folderCreatedCast) {
            let moreFileList = JSON.parse(window.sessionStorage.getItem('moreFileList'))
            await dispatch('ACTION_UPLOAD_FOLDER_PATH', moreFileList)
            console.log(fileList.value)
            resetUpladStatus(item)
          } else {
            resetUpladStatus(item)
          }
        } else {
          resetUpladStatus(item)
        }
      }
  } else {
    ElMessage.error('请检查当前网络')
  }
}

//重新上传-网络问题
async function reUploadStart() {
  //重新上传--断网或接口异常,仅限判断最后一次操作的文件/文件夹
  let foderFlag = window.sessionStorage.getItem('folderFlag')
  let testNetwork = await asyncGetData("getlist", '/公共空间').then(res => {
    const { data } = res;
    if (data.code == '200') {
      return true
    }
  }).catch(() => {
    testNetwork = false
  })
  //当前网络ok
  if (testNetwork) {
    await commit('ACTION_API_STATUS', false)
    //接口异常or网络失败中断
    if (!apiStatus.value) {
      //状态重置
      if (foderFlag === 'true') {
        //文件夹未创建--文件夹创建完毕--自动上传
        if (!props.folderCreatedCast) {
          let moreFileList = JSON.parse(window.sessionStorage.getItem('moreFileList'))
          await dispatch('ACTION_UPLOAD_FOLDER_PATH', moreFileList)
          console.log('[重新上传] ' + fileList.value)
          await resetUpladStatus()
          await commit('ACTION_UPLOAD_WAIT_STATUS', true)
        } else {
          await resetUpladStatus()
          await commit('ACTION_UPLOAD_WAIT_STATUS', true)
        }
      } else {
        await resetUpladStatus()
        await commit('ACTION_UPLOAD_WAIT_STATUS', true)
      }
    }
  } else {
    ElMessage.error('请检查当前网络')
  }
}

/**
 * 开始上传流程
 * @param {Object} file_item
 * @param {String} md5s
 * @param {String} file_index
 */
function uploadFileProcess(file_item, md5s, file_index) {
  let xmlHttp = new XMLHttpRequest();
  let sliceSize = 2048; // 默认切割 2M
  let file = {};
  file = file_item;
  console.log('[开始上传 uploadFileProcess ]vuex-recive-created--->' + folderAllCreated.value)
  console.log('[开始上传 uploadFileProcess ]props:folderState--->' + props.folderCreatedCast)
  //foloder all created start  upload.
  if (!file.webkitRelativePath) {
    console.log('开始切片上传 1')
    sliceUploaded(file, md5s)
  }
  if (props.folderCreatedCast) {
    console.log('开始切片上传 2')
    sliceUploaded(file, md5s)
  }
  
  /**
   * 服务端校验-上传
   * @param {Object} file
   * @param {String} md5s
   */
  function sliceUploaded(file, md5s) {
    let getPathLocal = window.sessionStorage.getItem("pathLocal");
    let new_name = file.name
    if (new_name.indexOf('&') > -1) {
      new_name = file.name.replace('&', '%26')
    }
    if (new_name.indexOf(`'`) > -1) {
      new_name = file.name.replace(/[\']/g, (v) => '\\' + v)
    }
    //uploadmeta - 这里简化处理，实际应用中需要使用axios或fetch发起请求
    // $.ajax({
    //   type: "get",
    //   url: `${http_path.value}/v1/oss/file`,
    //   data: {
    //     "action": 'uploadmeta',
    //     "fid": md5s,
    //     'path': file.uploadPath,
    //     'name': new_name,
    //     'size': file.size,
    //     "uid": yun_uid.value,
    //     'subid': sub_id.value,
    //     'corpid': crop_id.value,
    //     'groupid': groupid.value
    //   },
    //   dataType: 'json',
    //   contentType: 'application/x-www-form-urlencoded',
    //   crossDomain: 'true',
    //   success: function (data) {
    //     commit('ACTION_API_STATUS', false)
    //   },
    //   error: function (jqXHR, error, errorThrown) {
    //     if (jqXHR.status != '200') {
    //       commit('ACTION_API_STATUS', true)
        ElMessage.error('上传失败')
    //     }
    //   },
    // })
    
    // 由于是模拟环境，这里使用简化的上传逻辑
    setTimeout(() => {
      simulateUploadProcess(file, md5s)
    }, 1000)
  }
}

// 模拟上传过程
function simulateUploadProcess(file, md5s) {
  let progress = 0
  const interval = setInterval(() => {
    if (!file.upFileStatus || stopUpload.value) {
      clearInterval(interval)
      return
    }
    
    progress += Math.random() * 10
    if (progress >= 100) {
      progress = 100
      clearInterval(interval)
      file.domprogress = 100
      file.domstatus = '上传成功'
      file.upFileStatus = false
      file.dompercentmb = ''
      commit('ACTION_UPLOAD_WAIT_STATUS', true)
      commit('CHANGE_CANCEL_FLAG', true)
    } else {
      file.domprogress = Math.floor(progress)
      file.dompercentmb = `${(progress/100*file.size/1024/1024).toFixed(2)}MB/${(file.size/1024/1024).toFixed(2)}MB`
    }
  }, 200)
}

// click---触发点击按钮-上传类型
function selectFile() {
  if (!current_space.value) {
    if (uploadFile.value) uploadFile.value.click();
    stopUpload.value = false
  } else {
    ElMessage.error('当前空间容量不足')
  }
}

/**
 * change--上传监听
 * @param {Object} event
 */
async function tirggerFile(event) {
  commit('ACTION_UPLOAD_WAIT_STATUS', false) //上传时重置变量--等待状态
  let selectInputFile = Array.from(event.target.files)
  //base path build foloder, uplode complate refresh.
  let curent_path = window.sessionStorage.getItem('pathLocal')
  let relativePathList = []
  //if folder process path list
  if (__isFolderTip.value) {
    fileList.value = []
    selectInputFile.forEach(v => {
      let lastIndex = v.webkitRelativePath.lastIndexOf('/')
      let subText = v.webkitRelativePath.substring(lastIndex)
      let folder_path;
      //folder_path = folder_path.replace(/\s*/g, '')
      if (curent_path != '/') {
        folder_path = curent_path + '/' + v.webkitRelativePath.replace(subText, '')
      } else {
        folder_path = curent_path + v.webkitRelativePath.replace(subText, '')
      }
      relativePathList.push(folder_path)
    })
    window.sessionStorage.setItem('moreFileList', JSON.stringify(relativePathList))
      //send foloder list for api create foloder.
      await dispatch('ACTION_UPLOAD_FOLDER_PATH', relativePathList)
  }
  let curentArr = [...fileList.value]
  console.log('[tirggerFile] firstTimeUpload ' + firstTimeUpload.value)

  fileList.value = [...fileList.value, ...selectInputFile]
  //first send Array no data.
  //if not first time to touch it mark if close remove it.
  if (fileList.value.length > 0) {
    if (firstTimeUpload.value) {
      commit('ACTION_UPLOAD_WAIT_STATUS', true) //含有上传已完成的
      //for next upload switch ,Array last.
      firstTimeUpload.value = false
    }
    //prev list upload status all true touch upload.
    if (curentArr.length > 0) {
      let allCompleted = curentArr.every(v => v.domprogress && v.domprogress == '100')
      if (allCompleted) {
        firstTimeUpload.value = true
      }
    }
  }

  if (fileList.value.length > 0) {
    fileList.value.forEach((v, i) => {
      let reader = new FileReader()
      reader.readAsDataURL(v)
      if (apiStatus.value != true) {
        v.upFileStatus = true
        if (v.domprogress != '100') {
          v.domstatus = '排队中'
        }
      } else {
        if (v.domprogress != '100') {
          v.domstatus = '上传失败'
        }
      }
      v.md5Status = 0
      v.fileIndex = i
      v.net_speed = '';
      //if folder more path file upload.
      if (__isFolderTip.value) {
        //再次追加文件夹后两个数组个数不同--可在上步进行清空，无需合并
        relativePathList.forEach((v1, i1) => {
          if (!v.uploadPath) {
            if (i1 === i) {
              v.uploadPath = v1
            }
          }
        })
      } else {
        //only file upload.
        if (!v.uploadPath) {
          v.uploadPath = sessionStorage.getItem('pathLocal')
        }
      }
      if (v.type == "image/jpeg" || v.type == "image/png" || v.type == "image/jpg" || v.type == "image/svg" || v.type == "image/gif") {
        reader.onload = (e) => {
          v.pic = e.target.result
        }
      } else if (v.type == "video/x-msvideo" || v.type == "video/mpeg" || v.type == "video/quicktime" || v.type == "video/3gpp" || v.type == "video/mp4" || v.type == "video/avi") {
        v.pic = 'static/img/video.png'
      } else if (v.type == "audio/3gpp" || v.type == "audio/mp4" || v.type == "audio/x-aiff" || v.type == "audio/basic" || v.type == "audio/mpeg" || v.type == "audio/x-pn-realaudio" || v.type == "audio/ac3") {
        v.pic = 'static/img/icon-audio.png'
      } else if (v.type == "application/xhtml+xml" || v.type == "application/vnd.ms-excel" || v.type == "application/vnd.ms-excel" || v.type == "text/plain" || v.type == "text/rtf" || v.type == "application/rtf" || v.type == "application/vnd.ms-powerpoint" || v.type == "application/msword" || v.type == "application/msword" || v.type == "application/xml-dtd" || v.type == "text/html" || v.type == "application/pdf") {
        v.pic = 'static/img/icon-document.png'
      } else {
        v.pic = 'static/img/icon-unknown.png'
      }
    })
    //展开窗口
    maximize.value = false
    minmize.value = true
  }
  console.log('[input] tirggerFile ' + fileList.value + ' apiStatus err ' + apiStatus.value)
  //if (this.fileList.length > 0 && this.firstTimeUpload) {
  if (fileList.value.length > 0) {  
    //当前状态不可用时对于新添加的文件不予计算md5，让其触发当前排序第一个文件，或者不显示按钮
    if (apiStatus.value != true) {
      console.log('[firstTimeUpload ] 同步调用 uploadFile ')
      await uploadFileHandle()
    }
  }
  event.target.value = '';
}

//上传文件
async function uploadFileHandle() {
  dialogFormVisible.value = true;
  let checking = false;
  //按照队列进行计算文件
  let promise = Promise.resolve();
  fileList.value.forEach((item, index) => {
    promise = promise.then(() => {
      return new Promise(resolve => {
        setTimeout(() => {
          if (item.domprogress != 100) {
            if (checking === true) {
              return;
            }
            checking = true
            singleMd5(item)
          }
          if (upload_wait_status.value) {
            console.log('[uploadFile] resolve ok ' + item.name)
            resolve('ok');
          }
        }, 500);
      });
    })
  })

  //定义获取md5方法
  function singleMd5(file) {
    console.log('开始计算MD5 ' + file.name)
    let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
      chunkSize = 1024 * 1024 * 5, //每次读取5MB, // read in chunks of 5MB
      chunks = Math.ceil(file.size / chunkSize),
      currentChunk = 0,
      spark = new SparkMD5.ArrayBuffer(),
      chunksCount = Math.ceil(file.size / chunkSize),
      frOnload = function (e) {
        if (!fileList.value.length) {
          return
        }
        if (apiStatus.value) return
        fileList.value.forEach((v, i) => {
          if (v.name === file.name) {
            v.domstatus = "检查文件: " + (currentChunk + 1) + "/" + chunksCount
            if ((currentChunk + 1) === chunksCount && i != 0) {
              v.domstatus = '排队中'
            }
          }
        })
        spark.append(e.target.result); // append array buffer
        currentChunk++;
        if (currentChunk < chunks) {
          loadNext();
        } else {
          //文件md5状态设置完成
          file.md5Status = 1;
          file.md5File = spark.end();
          console.log("文件MD5结束，开始上传 fid：" + file.md5File + ' upload_wait_status  ' + upload_wait_status.value);
          if (upload_wait_status.value || file.fileIndex === 0 && file.domprogress != 100) {
            commit('ACTION_UPLOAD_WAIT_STATUS', false)
            uploadFileProcess(file, file.md5File, file.fileIndex)
          }
        }
      },
      frOnerror = function () { };
    function loadNext() {
      let fileReader = new FileReader();
      fileReader.onload = frOnload;
      fileReader.onerror = frOnerror;
      let start = currentChunk * chunkSize,
        end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
      fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
    };
    loadNext();
  }
}

//上传列表最小化点击
function minMizeClick() {
  maximize.value = true
  minmize.value = false
  uploadDialogFlag.value = false
}

//上传列表最大化
function maxMizeClick() {
  minmize.value = true
  maximize.value = false
  uploadDialogFlag.value = true
}

//上传框toggle
function uploadDialogToggle() {
  if (uploadDialogFlag.value) {
    minMizeClick()
  } else {
    maxMizeClick()
  }
}

/**
 * 上传地址点击
 * @param {String} path
 */
function uploadPathClick(path) {
  // 使用原生导航替代router
  navigateTo('/fileManage/fileManage', {
    filePath: path
  })
  sessionStorage.setItem('pathLocal', path)
  emit('uploadPath')
}

// 格式化函数
const sizeFormat = (size) => {
  if (!size) return '0 B'
  var unitArr = new Array('B', 'K', 'M', 'G');
  for (let i = 0; i < unitArr.length; i++) {
    if (Math.pow(1024, i + 1) > size) {
      return (size / (Math.pow(1024, i))).toFixed(2) + unitArr[i];
    }
  }
  return (size / (Math.pow(1024, 3))).toFixed(2) + 'G';
}

const pathFormat = (path) => {
  if (!path) return ''
  const lastPathIndex = path.lastIndexOf('/')
  let subText = path.substring(lastPathIndex)
  if (subText === '/') {
    subText = '我的空间'
  }
  return subText
}

// 创建一个应用实例
defineExpose({
  sizeFormat,
  pathFormat
})
</script>